/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pp.persistance;

import com.pp.entites.Traitement;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.pp.entites.Tube;
import com.pp.persistance.exceptions.NonexistentEntityException;
import com.pp.persistance.exceptions.PreexistingEntityException;
import com.pp.persistance.exceptions.RollbackFailureException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author arnaud
 */
public class TraitementJpaController implements Serializable {

    public TraitementJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Traitement traitement) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (traitement.getTubeList() == null) {
            traitement.setTubeList(new ArrayList<Tube>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<Tube> attachedTubeList = new ArrayList<Tube>();
            for (Tube tubeListTubeToAttach : traitement.getTubeList()) {
                tubeListTubeToAttach = em.getReference(tubeListTubeToAttach.getClass(), tubeListTubeToAttach.getId());
                attachedTubeList.add(tubeListTubeToAttach);
            }
            traitement.setTubeList(attachedTubeList);
            em.persist(traitement);
            for (Tube tubeListTube : traitement.getTubeList()) {
                tubeListTube.getTraitementList().add(traitement);
                tubeListTube = em.merge(tubeListTube);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findTraitement(traitement.getId()) != null) {
                throw new PreexistingEntityException("Traitement " + traitement + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Traitement traitement) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Traitement persistentTraitement = em.find(Traitement.class, traitement.getId());
            List<Tube> tubeListOld = persistentTraitement.getTubeList();
            List<Tube> tubeListNew = traitement.getTubeList();
            List<Tube> attachedTubeListNew = new ArrayList<Tube>();
            for (Tube tubeListNewTubeToAttach : tubeListNew) {
                tubeListNewTubeToAttach = em.getReference(tubeListNewTubeToAttach.getClass(), tubeListNewTubeToAttach.getId());
                attachedTubeListNew.add(tubeListNewTubeToAttach);
            }
            tubeListNew = attachedTubeListNew;
            traitement.setTubeList(tubeListNew);
            traitement = em.merge(traitement);
            for (Tube tubeListOldTube : tubeListOld) {
                if (!tubeListNew.contains(tubeListOldTube)) {
                    tubeListOldTube.getTraitementList().remove(traitement);
                    tubeListOldTube = em.merge(tubeListOldTube);
                }
            }
            for (Tube tubeListNewTube : tubeListNew) {
                if (!tubeListOld.contains(tubeListNewTube)) {
                    tubeListNewTube.getTraitementList().add(traitement);
                    tubeListNewTube = em.merge(tubeListNewTube);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = traitement.getId();
                if (findTraitement(id) == null) {
                    throw new NonexistentEntityException("The traitement with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Traitement traitement;
            try {
                traitement = em.getReference(Traitement.class, id);
                traitement.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The traitement with id " + id + " no longer exists.", enfe);
            }
            List<Tube> tubeList = traitement.getTubeList();
            for (Tube tubeListTube : tubeList) {
                tubeListTube.getTraitementList().remove(traitement);
                tubeListTube = em.merge(tubeListTube);
            }
            em.remove(traitement);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Traitement> findTraitementEntities() {
        return findTraitementEntities(true, -1, -1);
    }

    public List<Traitement> findTraitementEntities(int maxResults, int firstResult) {
        return findTraitementEntities(false, maxResults, firstResult);
    }

    private List<Traitement> findTraitementEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Traitement.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Traitement findTraitement(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Traitement.class, id);
        } finally {
            em.close();
        }
    }

    public int getTraitementCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Traitement> rt = cq.from(Traitement.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
